package com.storage.system.service.impl;

import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.enums.OwnerType;
import com.storage.common.enums.RoleType;
import com.storage.common.enums.UserAndAgentLevelType;
import com.storage.common.jpush.JiGuangPushUtil;
import com.storage.system.domain.StorageShop;
import com.storage.system.domain.StorageUser;
import com.storage.system.domain.StorageUserAgent;
import com.storage.system.mapper.StorageShopMapper;
import com.storage.system.mapper.StorageShopOrderMapper;
import com.storage.system.mapper.StorageUserAgentMapper;
import com.storage.system.service.IStorageShopService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 店铺 服务层实现
 *
 * @author storage
 * @date 2019-08-18
 */
@Service
public class StorageShopServiceImpl implements IStorageShopService {

    @Autowired
    private StorageShopMapper storageShopMapper;

    @Autowired
    private StorageUserAgentMapper storageUserAgentMapper;

    @Autowired
    private StorageShopOrderMapper storageShopOrderMapper;

    /**
     * 查询店铺信息
     *
     * @param id 店铺ID
     * @return 店铺信息
     */
    @Override
    public StorageShop selectStorageShopById(Long id) {
        return storageShopMapper.selectStorageShopById(id);
    }

    /**
     * 查询店铺列表
     *
     * @param storageShop 店铺信息
     * @return 店铺集合
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageShopList(StorageUser currentUser, StorageShop storageShop, Integer pageNum, Integer pageSize) {
        Long operationUserId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        storageShop.setCreateUserId(operationUserId);


        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;
        // 查询查询分页数据
        List<StorageShop> shops = storageShopMapper.queryPageList(storageShop, start, pageSize);
        // 查询totalCount
        Long totalCount = storageShopMapper.queryPageCount(storageShop);
        if (shops == null) {
            return null;
        }

        TableDataInfo pageList = new TableDataInfo(shops, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 新增店铺
     *
     * @param storageShop 店铺信息
     * @return 结果
     */
    @Override
    public AjaxResult insertStorageShop(StorageUser currentUser, StorageShop storageShop) {

        Long canOperationId = RoleType.getOperationUserId(currentUser.getRole(), currentUser.getId(), currentUser.getShopId());
        if (StringUtils.isBlank(storageShop.getShopName())) {
            return AjaxResult.error("店铺名称不能为空");
        } else if (storageShopMapper.selectStorageShopCountByName(storageShop.getShopName(), canOperationId) > 0) {
            return AjaxResult.error("已经存在相同的店铺名称");
        }
        storageShop.setCreateUserId(canOperationId);
        storageShopMapper.insertStorageShop(storageShop);

        // 建立店铺与代理商之间的上级代理商关联关系
        StorageUserAgent agent = new StorageUserAgent(currentUser.getId(), storageShop.getId(), UserAndAgentLevelType.DOWN.getValue(), OwnerType.SHOP.name(), null);
        StorageUserAgent shop = new StorageUserAgent(storageShop.getId(), currentUser.getId(), UserAndAgentLevelType.UP.getValue(), OwnerType.SHOP.name(), null);
        storageUserAgentMapper.insertStorageUserAgent(agent);
        storageUserAgentMapper.insertStorageUserAgent(shop);

        return AjaxResult.success("操作成功", storageShopMapper.selectStorageShopById(storageShop.getId()));
    }

    /**
     * 修改店铺
     *
     * @param storageShop 店铺信息
     * @return 结果
     */
    @Override
    public AjaxResult updateStorageShop(StorageUser currentUer, StorageShop storageShop) {
        if (StringUtils.isBlank(storageShop.getShopName())) {
            return AjaxResult.error("店铺名称不能为空");
        } else if (storageShopMapper.selectStorageShopCountByName(storageShop.getShopName(), currentUer.getId()) > 0) {
            return AjaxResult.error("已经存在相同的店铺名称");
        }
        storageShopMapper.updateStorageShop(storageShop);
        return AjaxResult.success("操作成功", storageShopMapper.selectStorageShopById(storageShop.getId()));
    }

    /**
     * 删除店铺对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public ServiceResponse<Boolean> deleteStorageShopByIds(String ids) {
        // 删除店铺与代理商之间的上下级关联关系
        String[] shopIds = ids.split(",");
        if (shopIds == null || shopIds.length == 0) {
            return new ServiceResponse<>(false, null, "店铺id不能为空");
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (String shopId : shopIds) {
            // 获取店铺创建者
            StorageShop shop = storageShopMapper.selectStorageShopById(Long.parseLong(shopId));

            // 查询出关联关系
            StorageUserAgent downAgent = storageUserAgentMapper.selectUserAgent(Long.parseLong(shopId), shop.getCreateUserId(), UserAndAgentLevelType.UP.getValue(), OwnerType.SHOP.name());
            StorageUserAgent upAgent = storageUserAgentMapper.selectUserAgent(shop.getCreateUserId(), Long.parseLong(shopId), UserAndAgentLevelType.DOWN.getValue(), OwnerType.SHOP.name());

            if (downAgent.getPaymentMoney() != null && upAgent.getPaymentMoney() != null
                    && Objects.equals(downAgent.getPaymentMoney().add(upAgent.getPaymentMoney()), new BigDecimal(0))) {
                stringBuilder.append(String.format("[%s] 不能删除，与代理商之间还存在 [%s] 结算金额未结清; ", shop.getShopName(), upAgent.getPaymentMoney()));
                continue;
            }

            // 删除店铺已经对应店铺与代理商之间的上下级关联关系
            storageUserAgentMapper.deleteStorageUserAgentById(downAgent.getId());
            storageUserAgentMapper.deleteStorageUserAgentById(upAgent.getId());
            storageShopMapper.deleteStorageShopById(shop.getId());
        }

        if (stringBuilder.toString().length() > 0) {
            return new ServiceResponse<>(false, null, stringBuilder.toString());
        }

        return new ServiceResponse<>(true, null, "删除成功");
    }

    /**
     * 查询店铺销售情况
     *
     * @param currentUser
     * @param storageShop
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServiceResponse<TableDataInfo> queryShopSellOrders(StorageUser currentUser, StorageShop storageShop, Integer pageNum, Integer pageSize) {
        // 查询当前所有销售订单 - 根据店铺id


//        storageShopOrderMapper.selectStorageShopOrderList()

        return null;
    }

}
